package com.jike.noobmoney.mvp.view.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.duoyou.ad.openapi.DyAdApi;
import com.jike.noobmoney.R;
import com.jike.noobmoney.adapter.TaskListAdapter;
import com.jike.noobmoney.contants.ConstantValue;
import com.jike.noobmoney.entity.BannerEntity;
import com.jike.noobmoney.entity.TaskListEntity;
import com.jike.noobmoney.helper.BannerHolderCreator;
import com.jike.noobmoney.mvp.presenter.TaskPresenter;
import com.jike.noobmoney.mvp.presenter.UserPresenter;
import com.jike.noobmoney.mvp.view.activity.DianCaiActivity;
import com.jike.noobmoney.mvp.view.activity.HotTopActivity;
import com.jike.noobmoney.mvp.view.activity.MainActivity;
import com.jike.noobmoney.mvp.view.activity.MessageActivity;
import com.jike.noobmoney.mvp.view.activity.MyEventActivity;
import com.jike.noobmoney.mvp.view.activity.MyTaskActivity;
import com.jike.noobmoney.mvp.view.activity.NewTaskActivity;
import com.jike.noobmoney.mvp.view.activity.PushTaskActivity;
import com.jike.noobmoney.mvp.view.activity.QianDaoActivity;
import com.jike.noobmoney.mvp.view.activity.TaskDetailActivity;
import com.jike.noobmoney.net.IView;
import com.jike.noobmoney.pcegg.PcEggActivity;
import com.jike.noobmoney.util.ComUtils;
import com.jike.noobmoney.util.SPUtils;
import com.jike.noobmoney.util.ToastUtils;
import com.jike.noobmoney.xq.XqActivity;
import com.lz.playmy.WowanIndex;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.toomee.mengplus.manager.TooMeeManager;
import com.zhouwei.mzbanner.MZBannerView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

import static android.app.Activity.RESULT_OK;

/**
 * Created by kekex on 2018/8/21.
 * 游戏任务
 */
public class TaskFragment extends BaseFragment implements View.OnClickListener, IView {

    @BindView(R.id.tv_center_title)
    TextView tvTitle;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.iv_message)
    ImageView ivMessage;
    Unbinder unbinder;
    @BindView(R.id.tv_corner)
    TextView tvCorner;
    @BindView(R.id.ll_message)
    RelativeLayout llMessage;
    private View headerView;
    private TaskListAdapter adapter;
    private List<TaskListEntity.TaskBean> mData = new ArrayList<>();
    private MZBannerView banner;
    private List<BannerEntity.HomeBean> mBannerData = new ArrayList<>();
    private List<String> images = new ArrayList<>();
    private TaskPresenter taskPresenter;

    private boolean isRefresh = true;
    private int page = 1;
    private UserPresenter userPresenter;
    private String userid = "";

    @Override
    public void onResume() {
        super.onResume();
        getRedrot();

        loadData(true);
    }

    @Override
    protected int layoutResID() {
        return R.layout.fragment_task;
    }

    @Override
    protected void initData() {
        tvTitle.setText("小白赚钱");
        llMessage.setVisibility(View.VISIBLE);
        ivMessage.setVisibility(View.VISIBLE);
        ivMessage.setOnClickListener(this);
        taskPresenter = new TaskPresenter(this);
        userPresenter = new UserPresenter(this);
        userid = SPUtils.getInstance().getString(ConstantValue.SpType.userid);
        initView();
        initListener();
        loadData(true);
    }

    private void getRedrot() {
        if (userPresenter != null) {
            userPresenter.getRedrot(userid, ConstantValue.RequestKey.message_num);
        }
    }

    private void setRedrot(String num) {
        if (TextUtils.isEmpty(num) || "0".equals(num)) {
            tvCorner.setVisibility(View.GONE);
        } else {
            tvCorner.setVisibility(View.VISIBLE);
            tvCorner.setText(num);
        }
    }

    private void initView() {
        headerView = LayoutInflater.from(context).inflate(R.layout.layout_head, null, false);
        headerView.findViewById(R.id.cardview_yaoqing).setOnClickListener(this);
        headerView.findViewById(R.id.cardview_kuaisu).setOnClickListener(this);
        headerView.findViewById(R.id.btn_kuaisu).setOnClickListener(this);
        headerView.findViewById(R.id.cardview_gaoe).setOnClickListener(this);
        headerView.findViewById(R.id.cardview_xingyun).setOnClickListener(this);
        headerView.findViewById(R.id.cardview_qq).setOnClickListener(this);


        banner = headerView.findViewById(R.id.banner);
        headerView.findViewById(R.id.ll_check_in).setOnClickListener(this);
        headerView.findViewById(R.id.ll_push_task).setOnClickListener(this);
        headerView.findViewById(R.id.ll_fast_task).setOnClickListener(this);
        headerView.findViewById(R.id.ll_invite_friends).setOnClickListener(this);
        headerView.findViewById(R.id.ll_shiwan).setOnClickListener(this);
        headerView.findViewById(R.id.ll_my_push).setOnClickListener(this);

        headerView.findViewById(R.id.iv_home_invite).setOnClickListener(this);
        headerView.findViewById(R.id.iv_home_gaoe).setOnClickListener(this);

        headerView.findViewById(R.id.iv_game1).setOnClickListener(this);
        headerView.findViewById(R.id.iv_game2).setOnClickListener(this);

        banner.setBannerPageClickListener((view, position) -> {
            if (mBannerData != null && mBannerData.size() > 0) {
                BannerEntity.HomeBean homeBean = mBannerData.get(position);
                String url = homeBean.getUrl();
                if ("0".equals(url)) {
                    //聚享玩
                    TooMeeManager.start(context);
                } else if ("1".equals(url)) {
                    //蛋蛋赚
                    Intent intent = new Intent();
                    intent.setClass(context.getApplicationContext(), WowanIndex.class);
                    startActivity(intent);
                } else if ("2".equals(url)) {
                    //邀请好友
                    MainActivity activity = (MainActivity) getActivity();
                    if (activity != null) {
                        activity.goRecommend(3);
                    }
                } else if ("3".equals(url)) {
                    //进qq群
                    ComUtils.startQQ(context, 3, "564104407");
                } else if ("4".equals(url)) {
                    //官方推荐
                    startActivity(new Intent(context, HotTopActivity.class));
                } else if (url.startsWith("http")) {
                    //跳转网页
                    if (url.contains("userid=")) {
                        String userid = SPUtils.getInstance().getString(ConstantValue.SpType.userid);
                        url = url + userid;
                    }
                    Intent intent = new Intent(context, MyEventActivity.class);
                    intent.putExtra(MyEventActivity.BUNDLE_KEY_URL, url);
                    startActivity(intent);
                }
            }
        });

        adapter = new TaskListAdapter(context);
        recyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
        recyclerView.setAdapter(adapter);
        adapter.setHeaderView(headerView);

    }

    private void initListener() {
        adapter.setOnItemClickListener((adapterView, view, position, l) -> {
            if (position == 0) {
                return;
            }
            TaskListEntity.TaskBean item = (TaskListEntity.TaskBean) adapter.getItem(position);

            Intent intent = new Intent(context, TaskDetailActivity.class);
            intent.putExtra(TaskDetailActivity.t_id, "" + item.getT_id());
            startActivity(intent);
        });

        refreshLayout.setOnRefreshListener(refreshlayout -> loadData(true));

        refreshLayout.setOnLoadMoreListener(refreshLayout -> loadData(false));
    }

    private void loadData(boolean isRefresh) {
        showProgressDialog();

        this.isRefresh = isRefresh;
        if (isRefresh) {
            page = 1;
        } else {
            page++;
        }

        if (taskPresenter != null) {
            taskPresenter.getBanner(ConstantValue.RequestKey.banner);
            taskPresenter.getJinRiList(userid, "0", "" + page, "10", ConstantValue.RequestKey.task_jinri_list);
        }
    }

    private void disLoad() {
        if (refreshLayout != null) {
            refreshLayout.finishRefresh();
            refreshLayout.finishLoadMore();
        }
        dismissProgressDialog();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.cardview_yaoqing:
                //邀请
                MainActivity activity = (MainActivity) getActivity();
                if (activity != null) {
                    activity.goRecommend(3);
                }
                break;
            case R.id.cardview_kuaisu:
            case R.id.btn_kuaisu:
                //快速任务
                Intent intent = new Intent();
                intent.setClass(context, WowanIndex.class);
                startActivity(intent);
                break;
            case R.id.cardview_gaoe:
                //高额任务
                TooMeeManager.start(context);
                break;
            case R.id.cardview_xingyun:
                //幸运
                String url = "http://engine.liulianqc.com/index/activity?appKey=ZgzfvSPbz5aG1JE1qsTrCeXWXyd&adslotId=485";
                startActivity(new Intent(context, MyEventActivity.class).putExtra(MyEventActivity.BUNDLE_KEY_URL, url));
                break;
            case R.id.cardview_qq:
                //QQ群
                ComUtils.startQQ(context, 3, "564104407");
                break;

            //-------------------------------2.0-----------------------------------
            case R.id.ll_check_in:
                //每日签到
                startActivityForResult(new Intent(context, QianDaoActivity.class), 200);
                //startActivity(new Intent(context, QianDaoActivity.class));
                break;
            case R.id.ll_fast_task:
                //快速任务 高额任务->简单任务  蛋蛋赚

//                String utoken = SPUtils.getInstance().getString(ConstantValue.SpType.utoken);
//                String imie = SPUtils.getInstance().getString(ConstantValue.SpType.imie);
//                if (TextUtils.isEmpty(utoken)) {
//                    ToastUtils.showShortToastSafe("用户获取失败");
//                }
//                String jxw = "http://task.juxiangwan.com/reward?utoken=" + utoken + "&mid=197&device_code=" + imie + "&sw=false";
//                Intent intent2 = new Intent(context, MyEventTwoActivity.class);
//                intent2.putExtra(MyEventTwoActivity.BUNDLE_KEY_URL, jxw);
//                intent2.putExtra(MyEventTwoActivity.BUNDLE_KEY_TITLE, "简单任务");
//                startActivity(intent2);

                DyAdApi.getDyAdApi().jumpAdList(context, userid, 0);
                DyAdApi.getDyAdApi().setTitleBarColor(R.color.maincolor);
                DyAdApi.getDyAdApi().setTitle(getString(R.string.app_name));
                break;
            case R.id.ll_shiwan:
                //游戏试玩 高额悬赏->试玩赚钱   聚享玩
                //Intent intent2 = new Intent();
                //intent2.setClass(context, WowanIndex.class);
                //startActivity(intent2);

                TooMeeManager.start(context);
                break;
            case R.id.ll_invite_friends:
                //邀请好友
//                MainActivity activity2 = (MainActivity) getActivity();
//                if (activity2 != null) {
//                    activity2.goRecommend(3);
//                }
                //配置落地页TitleBar的背景颜色和文字颜色
//                YmConfig.setTitleBarColors(0xfff8c45f, 0xffffffff);
//                YmConfig.openReader();
                startActivity(new Intent(context, DianCaiActivity.class));
                break;
            case R.id.ll_push_task:
                //发布任务
                startActivity(new Intent(context, PushTaskActivity.class));
                break;
            case R.id.ll_my_push:
                //我的任务
                startActivity(new Intent(context, MyTaskActivity.class));
                break;
            case R.id.iv_home_invite:
                //新手任务
                startActivityForResult(new Intent(context, NewTaskActivity.class), 200);
                break;
            case R.id.iv_home_gaoe:
                //官方推荐
                startActivity(new Intent(context, HotTopActivity.class));
                break;
            case R.id.iv_message:
                //消息
                startActivity(new Intent(context, MessageActivity.class));
                break;
            case R.id.iv_game1:
                //pc蛋蛋
                PcEggActivity.startActivity(context, "", userid);
                break;
            case R.id.iv_game2:
                //嘻趣
                XqActivity.startActivity(context, "3251", "wsfhnb1v8sxbzq71", userid);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 200 && resultCode == RESULT_OK) {
            MainActivity activity2 = (MainActivity) getActivity();
            if (activity2 != null) {
                //任务大厅
                activity2.goRecommend(2);
            }
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        //开始轮播
//        if (banner != null) {
//            banner.startAutoPlay();
//        }
        if (banner != null) {
            banner.start();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        //结束轮播
//        if (banner != null) {
//            banner.stopAutoPlay();
//        }

        if (banner != null) {
            banner.pause();
        }
    }


    @Override
    public void onSuccess(String code, String msg, Object data, String actionType) {
        if (ConstantValue.RequestKey.banner.equals(actionType)) {
            List<BannerEntity.HomeBean> data1 = (List<BannerEntity.HomeBean>) data;
            if (data1 != null && data1.size() > 0) {
                mBannerData.clear();
                mBannerData.addAll(data1);
            }
            setBanner(mBannerData);
        }

        if (ConstantValue.RequestKey.task_jinri_list.equals(actionType)) {
            List<TaskListEntity.TaskBean> task = (List<TaskListEntity.TaskBean>) data;
            if (task != null && task.size() > 0) {
                if (isRefresh) {
                    mData.clear();
                    mData.addAll(task);
                } else {
                    mData.addAll(task);
                }
            }else{
                ToastUtils.showLongToast("没有更多数据了");
            }

            adapter.refresh(mData);
        }

        if (ConstantValue.RequestKey.message_num.equals(actionType)) {
            String number = (String) data;
            setRedrot(number);
        }

        disLoad();
    }

    private void setBanner(List<BannerEntity.HomeBean> data) {
        images.clear();
//        for (int i = 0; i < data.size(); i++) {
//            images.add(ConstantValue.IMG_BASEURL + data.get(i).getPicture());
//        }
//        banner.setImageLoader(new GlideImageLoader()).setDelayTime(5000).setImages(images).start();
//        banner.setOnBannerListener(position -> {
//            BannerEntity.HomeBean homeBean = data.get(position);
//            String url = homeBean.getUrl();
//            Logger.e("xuke", url);
//            if (url.contains("http")) {
//                startActivity(new Intent(context, MyEventActivity.class).putExtra(MyEventActivity.BUNDLE_KEY_URL, url));
//            }
//        });


        if (data.size() > 0) {
            banner.setVisibility(View.VISIBLE);
            final List<String> images = new ArrayList<>();
            for (int i = 0; i < data.size(); i++) {
                images.add(ConstantValue.IMG_BASEURL + data.get(i).getPicture());
            }
            BannerHolderCreator bannerHolderCreator = new BannerHolderCreator();
            banner.setPages(images, bannerHolderCreator);

            //切换时间间隔
            banner.setDelayedTime(5000);
            banner.setDuration(2000);
            banner.start();
        } else {
            banner.setVisibility(View.GONE);
        }
    }

    @Override
    public void onFailed(String code, String msg) {
        disLoad();
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
